package com.chookss.home.search.fragment;


import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.home.document.DocumentPreviewActivity;
import com.chookss.home.search.adapter.SearchDataAdapter;
import com.chookss.home.search.entity.SearchAllEntity;
import com.chookss.tools.AESEncrypt;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.RecycleViewDivider;
import com.google.gson.reflect.TypeToken;
import com.liulishuo.okdownload.DownloadTask;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.annotations.NonNull;

@SuppressLint("ValidFragment")
public class SearchDataFragment extends SearchBaseFragment {

    public Context mContext;
    Unbinder unbinder;
    @BindView(R.id.srlView)
    SmartRefreshLayout srlView;
    @BindView(R.id.rvView)
    RecyclerView rv;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.tvNone)
    TextView tvNone;
    @BindView(R.id.ivNone)
    ImageView ivNone;
    private SearchDataAdapter adapter;
    private List<SearchAllEntity.DataBean.ListBean> list = new ArrayList<>();
    private int currentPage = 1;
    private String pageSize = "20";
    private boolean isEnd = false;//是否到底
    private String localKey = "", localType = "0";

    public SearchDataFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_search_base, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        //注册接受
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onViewStateRestored(@androidx.annotation.Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
    }

    private void init() {
        rv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        rv.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.HORIZONTAL, Utils.dip2px(mContext, 0.5f), getResources().getColor(R.color.line_gray)));
        adapter = new SearchDataAdapter(R.layout.item_search_data_list, mContext, list, "SearchDataFragment_DownloadFile");
        rv.setAdapter(adapter);
        rv.getItemAnimator().setAddDuration(0);
        rv.getItemAnimator().setChangeDuration(0);
        rv.getItemAnimator().setMoveDuration(0);
        rv.getItemAnimator().setRemoveDuration(0);
        ((SimpleItemAnimator) rv.getItemAnimator()).setSupportsChangeAnimations(false);
        rv.setItemAnimator(null);
        srlView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        srlView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                isEnd = false;
                currentPage = 1;
                getData();
                srlView.setEnableRefresh(false);
            }
        });
        registerBoradcastReceiver();
    }

    @Override
    public void onVisible() {
        super.onVisible();
        if (srlView == null) {
            return;
        }
        if (Utils.isNull(localKey)) {
            srlView.autoRefresh();
        } else {
            if (localKey.equals(key) && localType.equals(searchType)) {
            } else {
                srlView.setEnableRefresh(true);
                srlView.autoRefresh();
            }
        }
    }

    @Override
    public void refreshData() {
        if (srlView == null) {
            return;
        }
        srlView.setEnableRefresh(true);
        srlView.autoRefresh();
    }

    private void getData() {
        localKey = key;
        localType = searchType;
        adapter.setKey(localKey);
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        map.put("word", key);
        map.put("searchType", searchType);
        map.put("itemType", "data");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<SearchAllEntity>>() {
        }.getType(), null, Urls.selectForSearch, SignUtils2.makeSignStr(map), false, new ObserverCallback<SearchAllEntity>() {
            @Override
            public void onSuccess(SearchAllEntity data) {
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                loadEnd();
                if (srlView == null || llNone == null) {
                    return;
                }
                if (data.getData() == null) {
                    isEnd = true;
                    if (list.size() == 0) {

                        srlView.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                        String init = "抱歉，没用找到关于“<font color='#666666'>" + key + "</font>”的资料";
                        tvNone.setText(Html.fromHtml(init));
                    }
                    return;
                }
                if (data.getData().getList() != null && data.getData().getList().size() > 0) {
                    list.addAll(data.getData().getList());
                    adapter.notifyDataSetChanged();
                    srlView.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        srlView.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                        String init = "抱歉，没用找到关于“<font color='#666666'>" + key + "</font>”的资料";
                        tvNone.setText(Html.fromHtml(init));
                    }
                }

            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    @Override
    public void initImmersionBar() {

    }

    private void loadEnd() {
        if (null != srlView && srlView.getState() == RefreshState.Refreshing)
            srlView.finishRefresh(true);
        if (null != srlView && srlView.getState() == RefreshState.Loading)
            srlView.finishLoadMore(true);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            HashMap<String, String> map = messageEvent.getHashMap();
            if(map.containsKey("DocumentPreview_error")){
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getDataCode().equals(map.get("DocumentPreview_error"))) {
                        list.get(i).setError(true);
                    }
                }

            }
        }
    }


    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                int position = intent.getIntExtra("position", 0);
                int percent = intent.getIntExtra("percent", 0);
                String recevierDataCode = intent.getStringExtra("dataCode");
                boolean encryptStatus = intent.getBooleanExtra("encryptStatus", false);
                String fileUrl = intent.getStringExtra("fileUrl");
                String fileName = intent.getStringExtra("fileName");
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getDataCode().equals(recevierDataCode)) {
                        if (!list.get(i).isOpen()) {
                            if(encryptStatus){
                                list.get(i).setOpen(true);
                            }
                            dealData(position, percent, recevierDataCode, encryptStatus, fileUrl, fileName);
                        }

                    }
                }

            }
        }

    };

    /**
     * @param position
     * @param percent
     * @param recevierDataCode 处理广播数据
     * @param encryptStatus
     * @param fileUrl
     * @param fileName
     */
    private void dealData(int position, int percent, String recevierDataCode, boolean encryptStatus, String fileUrl, String fileName) {

        if (encryptStatus) {
            if (!MyApp.docunmentOpen) {
                Intent newIntent = new Intent(mContext, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                startActivity(newIntent);
            }
        } else {
            if (percent > 0 && percent < 100) {
                if (adapter != null) {
                    list.get(position).setProgress(percent);
                    adapter.notifyItemChanged(position);
                }
            } else if (percent == 100) {
                if (adapter != null) {
                    list.get(position).setProgress(100);
                    adapter.notifyItemChanged(position);
                    new Thread() {
                        @Override
                        public void run() {
                            AESEncrypt.encryptFile(mContext, fileUrl, fileName, recevierDataCode, "SearchDataFragment_DownloadFile");
                        }
                    }.start();
                }


            }else if (percent == 0) {
                //正常情况不会0
                Intent newIntent = new Intent(mContext, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                newIntent.putExtra("isError", true);
                startActivity(newIntent);
            }
        }
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction("SearchDataFragment_DownloadFile");// 获取数据
        LocalBroadcastManager.getInstance(mContext).registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        HashMap<String, DownloadTask> map = MyApp.downloadTaskHashMap;
        for (String key : map.keySet()) {
            DownloadTask task = map.get(key);
            if (task != null) {
                task.cancel();
            }
        }
        if (mBroadcastReceiver != null && mContext != null) {
            LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mBroadcastReceiver);
        }
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }

}
